from flask import session, render_template, current_app, jsonify, request, g

from info import db
from . import news_blue
from info.models import User, News, Category
from info.utils.commons import login_required
from info.utils.response_code import RET


@news_blue.route('/')
# @login_required
def index():
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻点击排行数据失败')
    if not news_clicks:
        return jsonify(errno=RET.NODATA, errmsg='新闻点击排行数据为空')
    news_rank = []
    # 便利查询结果
    for news in news_clicks:
        news_rank.append(news.to_dict())

    # 查询新闻分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询分类数据失败')
    # 判断查询结果
    if not categories:
        return jsonify(errno=RET.NODATA, errmsg='无分类数据')
    # 定义容器存储查询结果
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    # 从redis中获取user_id
    user_id = session.get('user_id')
    data = None
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
            user = None
    data = {
        'user_info': user.to_dict() if user else None,
        'news_rank': news_rank,
        'category_list': category_list
    }
    return render_template('news/index.html', data=data)


@news_blue.route('/news_list')
def get_news_list():
    """
    首页新闻列表数据
    1. 尝试获取参数, cid,page,per_page
    2. 如果没有需要给默认值
    request.args.get("cid",'1')
    3. 把页数和每页的条目进行强制转换int
    4. 根据分类id查询数据科，按照新闻的发布时间进行排序，使用pageinate进行分页
    5. 获取分页对象
    6. 使用分页对象， 获取分页后的新闻数据
    paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,per_page,False)
    news_date = paginate.items --->总新闻数据
    total_page = paginate.pages ---->总页数
    current_page = paginate.page ---> 当前页数
    7. 遍历分页后的总页数，定义容器，调用to_dict()
    8. 返回结果：总页数，当前页数，新闻列表数据
    :return:
    """
    # 获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    # 对页数和每页的条目进行强转
    try:
        page, per_page = int(page), int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数格式错误')
    # 定义查询的过滤条件
    filters = []
    # 如果分类id不是最新，添加查询条件
    if cid != '1':
        filters.append(News.category_id == cid)

    # 根据分类id查询数据库
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻列表数据失败')
    # 获取分页后的新闻数据/总页数/当前页数
    news_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    # 定义列表存储查询结果
    news_dict_list = []
    # 遍历分页后的新闻数据
    for news in news_list:
        news_dict_list.append(news.to_dict())
    # 构造响应报文
    data = {
        'news_dict_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@news_blue.route('/<int:news_id>')
@login_required
def news_detail(news_id):
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')
    # 判断查询结果
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='无新闻数据')
    news.clicks += 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻点击排行数据失败')
    if not news_clicks:
        return jsonify(errno=RET.NODATA,errmsg='无新闻点击排行数据')
    news_rank = []
    for news_index in news_clicks:
        news_rank.append(news_index.to_dict())
    is_collected = False
    if g.user:
        if news in g.user.collection_news:
            is_collected = True
    user = g.user
    data = {
        'news': news.to_dict(),
        'is_collected':is_collected,
        'news_rank': news_rank,
        'user_info': user.to_dict() if user else None,
    }
    return render_template('news/detail.html', data=data)


@news_blue.route('/news_collect', methods=['POST'])
@login_required
def news_collect():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='新闻id格式错误')
    if action not in ['cancel_collect', 'collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='收藏操作不在范围内')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='收藏时查询新闻id失败')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='收藏操作时没有查询到新闻数据')
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')


# 创建网页的路标favicon
@news_blue.route('/favicon.ico')
def favicon():
    # falsk 默认创建静态路由，把favicon放在static文件夹的下面，拼接路径返回给浏览器
    # http://127.0.0.1:5000/static/
    return current_app.send_static_file('news/favicon.ico')
